package framework;

import java.awt.Dimension;

import javafx.application.Platform;
import javafx.embed.swing.JFXPanel;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;

import javax.swing.JFrame;

import framework.webclient.ProxyData;

public class JavaFxFrameworkUi implements FrameworkUi {
	private JFrame statusFrame;
	private LoginHandler loginHandler;
	
	public JavaFxFrameworkUi() {
		JFXPanel dummy = new JFXPanel(); // to avoid Platform initializable error
	}
	
	@Override
	public void setLoginStatusVisible(final boolean b) {
		setVisible(b);
	}

	private JFrame showLoginStatus() {
		final JFrame statusFrame = new JFrame();
		statusFrame.setLocationRelativeTo(null);
	//	statusFrame.setUndecorated(true);
		statusFrame.setSize(new Dimension(200,100));
		final JFXPanel fxPanel = new JFXPanel();
		Platform.runLater(new Runnable() {
			@Override
			public void run() {
				statusFrame.add(fxPanel);		
				AnchorPane root = new AnchorPane();
				root.setStyle("-fx-font-size:20px;");
				Scene  scene  =  new  Scene(root, Color.ALICEBLUE);
				VBox vbox = new VBox();
				root.getChildren().add(vbox);
//				ProgressIndicator pi = new ProgressIndicator(0.6);
				vbox.getChildren().add(new Label("Logging In..."));
				//vbox.getChildren().add(pi);
				fxPanel.setScene(scene);
				statusFrame.setVisible(true);
			}
		});

		return statusFrame;
	}

	private void setVisible(final boolean b) {
		if (b) {
			statusFrame = showLoginStatus();
		}
		Platform.runLater(new Runnable() {

			@Override
			public void run() {
				statusFrame.setVisible(b);
			}
			
		});
	}

	@Override
	public void createLoginUi(final LoginHandler loginHandler) {
		Platform.runLater(new Runnable() {
			@Override
			public void run() {
				final JFrame frame = new JFrame();
				frame.setLocationRelativeTo(null);
				final JFXPanel fxPanel = new JFXPanel();
				frame.add(fxPanel);
				frame.setSize(new Dimension(300, 300));
				LoginPane loginPane = new LoginPane();

				final Scene  scene  =  new  Scene(loginPane, Color.ALICEBLUE);
				fxPanel.setScene(scene);

				loginPane.setOnOk(new LoginHandler() {

					@Override
					public void onOK(String account, String password,
							ProxyData proxy) {
						frame.setVisible(false);
						loginHandler.onOK(account, password, proxy);
					}
					
				});
				frame.setVisible(true);
			}
		});
	}

}
